package com.wyl.coroutinesapp

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.wyl.coroutinesapp.util.LogUtil
import kotlinx.coroutines.*

/**
 * 【Kotlin】协程（一）——入门 https://www.jianshu.com/p/96ac85beb8fd
 * 快速入门
 * 1.开启协程 --launch
 *  挂起协程: join()
 * 2.切换线程 withContext()--会挂起协程
 * 3.async --开启协程的另一种方式
 *  挂起协程: await()
 */
@SuppressLint("SetTextI18n")
class QuickFragment : Fragment() {
    private val mainScope = MainScope()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_quick, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        LogUtil.d("1.onActivityCreated start")
        mainScope.launch {
//            launch1()
//            launch2(this)
            async1(this)
        }
        LogUtil.d("2.onActivityCreated end")
    }


    private suspend fun async1(scope: CoroutineScope) {
        val token = scope.async(Dispatchers.Default) {
            printThreadName()
            LogUtil.d("4.async end")
            "token"
        }
        LogUtil.d("3.launch end")

        LogUtil.d("5. token = ${token.await()}")
    }

    private fun launch2(scope: CoroutineScope) {
        scope.launch(Dispatchers.Default) {
            printThreadName()
            LogUtil.d("4.launch end")
        }
        LogUtil.d("3.launch end")
    }

    private suspend fun launch1() {
        LogUtil.d("3.launch start")
        withContext(Dispatchers.Default) {
            LogUtil.d("4.Dispatchers.Default")
            printThreadName()
        }
        printThreadName()
        withContext(Dispatchers.Main) {
            LogUtil.d("5.Dispatchers.Main")
            printThreadName()
        }
        printThreadName()
        withContext(Dispatchers.IO) {
            LogUtil.d("6.Dispatchers.IO")
            printThreadName()
        }
        printThreadName()
        withContext(Dispatchers.Unconfined) {
            LogUtil.d("7.Dispatchers.Unconfined")
            printThreadName()
        }
        printThreadName()
        LogUtil.d("3.launch end")
    }

    private fun printThreadName() = LogUtil.d(Thread.currentThread())

    override fun onDestroy() {
        mainScope.cancel()
        super.onDestroy()
    }

}
